<template>
  <el-dialog :title="action === 'add' ? '新增' : '修改'" width="30%" draggable
              :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmit(dataFormRef)" label-width="80px">
      <el-form-item label="上级部门">
        <el-input v-model="dataForm.pname" disabled />
      </el-form-item>
      <el-form-item label="部门代码" prop="code">
        <el-input v-model="dataForm.code" minlength="2" maxlength="50" placeholder="部门代码" />
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="dataForm.name" minlength="2" maxlength="20" placeholder="部门名称" />
      </el-form-item>
      <el-form-item label="部门排序" prop="sort">
        <el-input-number v-model="dataForm.sort" :min="1" :max="10000" label="部门排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

// 操作：add-新增，update-修改
const action = ref("");

// 弹窗是否显示
const visible = ref(false);

// 提交按钮是否禁用
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  id: undefined,
  pid: undefined,
  pname: "",
  code: "",
  name: "",
  sort: 0,
  icon: "",
  description: "",
});

// 表单校验规则
const dataRule = reactive({
  code: validate.required("部门代码"),
  name: validate.required("部门名称"),
  type: validate.required("部门排序"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 父级组件的自定义事件
const emit = defineEmits(['initDepartTreeData']);

// 表单初始化
const initForm = async (a, n) => {
  action.value = a;
  // 新增跟节点
  if (a === "add-root") {
    visible.value = true;
    await nextTick();
    dataFormRef.value.resetFields();
    dataForm.id = undefined;
    dataForm.pid = undefined;
    dataForm.code = "";
    dataForm.name = "";
    dataForm.pname = "跟节点";
    dataForm.sort = n && n.length > 0 && n[n.length - 1].sort + 1;
    return;
  }
  // 新增子节点操作
  if (a === "add-node") {
    // 新增表单初始化
    visible.value = true;
    await nextTick();
    dataFormRef.value.resetFields();
    dataForm.id = undefined;
    dataForm.pid = n && n.id;
    dataForm.code = "";
    dataForm.name = "";
    dataForm.pname = n && n.name;
    dataForm.sort = n.children && n.children.length > 0 && n.children[n.children.length - 1].sort + 1;
    return;
  }
  // 修改操作
  dataForm.id = n.id;
  http
    .post({
      url: "/depart/info",
      params: { departId: dataForm.id, details: "Y" },
    })
    .then(async ({ data }) => {
      if (http.success(data)) {
        visible.value = true;
        await nextTick();
        dataFormRef.value.resetFields();
        dataForm.id = data.body.id;
        dataForm.pid = data.body.pid;
        dataForm.pname = data.body.pname;
        dataForm.code = data.body.code;
        dataForm.name = data.body.name;
        dataForm.sort = data.body.sort;
        dataForm.icon = data.body.icon;
        dataForm.description = data.body.description;
      }
    });
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: "/depart/save",
          data: {
            id: dataForm.id || undefined,
            pid: dataForm.pid,
            code: dataForm.code || undefined,
            name: dataForm.name || undefined,
            sort: dataForm.sort || undefined,
            icon: dataForm.icon || undefined,
            description: dataForm.description || undefined,
          },
        })
        .then(({ data }) => {
          if (http.success(data, true, true)) {
            visible.value = false;
            emit("initDepartTreeData");
            return;
          }
          submitted.value = false;
        });
    }
  });
};

// 暴露方法
defineExpose({ initForm });
</script>
